package gatewayservice.gatewayservice;

import gatewayservice.gatewayservice.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;


@Component
public class AuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("=== 进入过滤器 ===");
        System.out.println("请求路径: " + exchange.getRequest().getURI().getPath());
        System.out.println("Headers: " + exchange.getRequest().getHeaders());
        System.out.println("QueryParams: " + exchange.getRequest().getQueryParams());
        // 1. 放行登录接口（按需启用）
        String path = exchange.getRequest().getURI().getPath();
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }

        // 2. 获取Token（Header优先，兼容Query）
        String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");
        String token = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            token = exchange.getRequest().getQueryParams().getFirst("token");
        }

        System.out.println("Extracted token: " + token);

        // 3. 严格判空
        if (token == null || token.trim().isEmpty()) {
            System.out.println("Blocking request: No token provided");
            //响应http状态码（401）
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //请求结束
            return exchange.getResponse().setComplete();
        }

        // 4. 验证Token
        try {
            JwtUtils.parseJWT("yunyuansheng", token);
            System.out.println("Token验证成功");
        } catch (Exception e) {
            System.out.println("Token验证失败: " + e.getMessage());
            //响应http状态码（401）
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //请求结束
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }
}